<template>
  <div class="el-card__body">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div>
          <el-form :inline="true" :model="searchform" class="demo-form-inline">
            <el-form-item label="标签名称">
              <el-input
                v-model="searchform.tagName"
                placeholder="标签名称"
                @keyup.enter="onSubmit"
              ></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchform.state" placeholder="请选择">
                <el-option
                  v-for="item in status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="resetForm">清除</el-button>
              <el-button type="primary" @click="onSubmit">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- 新增 -->
        <el-button
          class="filter-item fr"
          size="small"
          style="margin-left: 10px"
          @click="handleAdd"
          type="success"
          icon="el-icon-edit"
          >新增标签
        </el-button>
        <!-- Alert 警告 -->
        <div
          role="alert"
          class="el-alert alert el-alert--info is-light"
          style="margin-bottom: 15px">
          <i class="el-alert__icon el-icon-info"></i>
          <div class="el-alert__content">
            <span class="el-alert__title">数据一共 {{ total }} 条</span>
            <i
              class="el-alert__closebtn el-icon-close"
              style="display: none"
            ></i>
          </div>
        </div>
        <!-- 表格 -->
        <el-table :data="tableData" style="width: 100%" :total="total">
          <el-table-column type="index" prop="id" label="序号" width="100">
          </el-table-column>
          <el-table-column prop="subjectName" label="所属学科" width="100">
          </el-table-column>
          <el-table-column prop="tagName" label="标签名称">
          </el-table-column>
          <el-table-column prop="username" label="创建者">
          </el-table-column>
          <el-table-column prop="addDate" label="创建日期" width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.addDate | date }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="totals" label="面试题数量">
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template slot-scope="scope">
              <span v-if="scope.row.state == 1">启用</span>
              <span v-else>禁用</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="handledisable(scope.row)" >
                <span>{{ scope.row.state === 0 ? "启用" : "禁用" }}</span>
              </el-button>
              <el-button
                type="text"
                size="small"
                @click.native="handleEdit(scope.row)"
                :disabled="scope.row.state == 1 ? true : false"
                >修改</el-button>
              <el-button
                type="text"
                size="small"
                @click="handleDelete(scope.row)"
                :disabled="scope.row.state == 1 ? true : false"
                >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
          <div style="margin-top: 20px; text-align: right" class="pagination" v-show="total">
          <div  class="pages">
           <el-pagination
           @size-change="handleSizeChange"
            background
            layout="sizes, prev, pager, next, jumper"
            :total="total"
            @current-change="Hpager"
            :page-size="100"
            :page-sizes="[10,20,30, 50]"
          >
           </el-pagination>
         </div>
        </div>
      </div>
    </el-card>
    <!-- 新增/编辑提示框 -->
    <el-dialog
      :title="dialogTitle"
      :item-info="formData"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <el-form
        label-width="100px"
        class="demo-ruleForm"
        :model="formData"
        :rules="rules"
        ref="formData">
        <el-form-item
          label="所属学科"
          prop="subjectName"
          v-model="formData.subjectName">
          <el-select placeholder="请选择科目" v-model="subjectID">
            <el-option
              v-for="item in subiectList"
              :key="item.id"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" prop="tagName">
          <el-input v-model="formData.tagName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click.prevent="hconfirmAdd(formData)"
          v-if="addBtnshow"
          >确 定</el-button>
        <el-button
          v-if="editBtnshow"
          type="primary"
          @click.prevent="hconfirmEdit(formData)"
          >确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// eslint-disable-next-line import/no-duplicates
import { list as getcatalog, changeState, update, remove, add } from '@/api/hmmm/tags.js'
import { status } from '@/api/hmmm/constants'
import { simple } from '../../api/hmmm/subjects'
export default {
  name: 'subJect',
  data () {
    return {
      rules: {
        subjectName: [{ required: false, message: '', trigger: 'change' }],
        tagName: [
          { required: true, message: '请输入标签名称', trigger: 'blur' },
          { min: 1, max: 9, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      form: {
        addDate: Date() // 定义当前的时间
      },
      // 搜索
      searchform: {
        subjectName: '', // 所属科学
        state: null // 状态
      },
      // 新增编辑
      formData: {
        subjectName: '', // 所属科学
        tagName: '', // 科目名称
        id: ''
      },
      dialogTitle: '',
      tableData: [], // 表格数据
      total: 0, // 总页码
      page: 1,
      dialogVisible: false, // 弹框关闭
      subiectList: [], // 学科列表
      subjectID: '', // 学科Id
      addBtnshow: false, // 添加按钮
      editBtnshow: false // 编辑按钮
    }
  },
  created () {
    this.loadDirectorys()
  },
  computed: {
    status () {
      return status
    }
  },
  methods: {
    // 按钮操作
    // 按钮点击状态
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    async buildSatus (row) {
      const sta = {
        id: row.id,
        // 状态取反
        state: Number(!row.state)
      }
      console.log(sta)
      // 改变状态
      await changeState(sta)
        .then((response) => {
          this.$message.success('操作成功!')
          this.loadDirectory(this.form)
        })
        .catch((response) => {
          this.$message.error(status + '失败!')
        })
    },
    // 禁用启用
    handledisable (row) {
      this.buildSatus(row)
      this.$message.success('操作成功')
    },
    // 新增功能
    handleAdd () {
      this.formData = {
        subjectName: '', // 所属科学
        tagName: '' // 科目名称
      }
      this.dialogTitle = '增加标签'
      // 打开弹窗
      this.dialogVisible = true
      // 打开添加按钮
      this.addBtnshow = true
      // 关闭编辑按钮
      this.editBtnshow = false
      // 获取科目详情
      this.subjectList()
      // 清空表单中的值
      this.subjectName = ''
      this.subjectID = ''
    },
    // 组装一个保存参数方法
    saveParams () {
      const paramsa = {
        tagName: this.formData.tagName,
        subjectID: this.subjectID
      }
      return paramsa
    },
    // 新增功能表单验证
    hconfirmAdd () {
      // 去检查一下表单元素中验证是否全部通过
      // this.$refs.form: 就是上面添加了ref的那个表单组件
      // validate就是表单组件提供的方法
      // console.log(this.$refs.form)
      this.$refs.formData.validate((valid) => {
        // valid 就是表单验证的结果，如果是true，表示通过了
        // console.log(valid)
        if (valid) {
          this.confirmAdd()
        }
      })
    },
    // 新增保存功能
    async confirmAdd () {
      const paramsa = this.saveParams()
      try {
        await add(paramsa)
        this.$message.success('添加成功')
        this.subjectList()
        this.loadDirectory()
        // eslint-disable-next-line no-unused-expressions
        this.page === 1
        this.dialogVisible = false
      } catch (err) {
        this.$message.error('添加失败')
      }
    },
    // 获取科目列表
    async subjectList () {
      const res = await simple()
      console.log(res)
      this.subiectList = res.data
    },
    // 修改功能
    handleEdit (row) {
      this.dialogVisible = true
      this.formData = row
      this.subjectID = row.subjectID
      console.log(row)
      // 当前标题显示编辑标签
      this.dialogTitle = '修改标签'
      // 请求数据
      this.subjectList()
      this.addBtnshow = false
      this.editBtnshow = true
    },
    //  保存修改功能
    async confirmEdit () {
      const params = {
        id: this.formData.id,
        tagName: this.formData.tagName,
        subjectID: this.subjectID
      }
      try {
        await update(params)
        this.$message.success('修改成功')
        // // 重新请求数据
        this.loadDirectory()
        this.dialogVisible = false
      } catch (err) {
        console.log(err)
        this.$message.error('修改失败')
      }
    },
    // 编辑功能表单验证
    hconfirmEdit () {
      // 去检查一下表单元素中验证是否全部通过
      // this.$refs.form: 就是上面添加了ref的那个表单组件
      // validate就是表单组件提供的方法
      // console.log(this.$refs.form)
      this.$refs.formData.validate((valid) => {
        // valid 就是表单验证的结果，如果是true，表示通过了
        // console.log(valid)
        if (valid) {
          this.confirmEdit()
        }
      })
    },
    // 删除功能
    async hDelete (id) {
      try {
        await remove(id)
        this.$message.success('删除成功')
        this.loadDirectorys()
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败')
      }
    },
    handleDelete (userid) {
      this.$confirm('你确定要删除吗?')
        .then(() => {
          this.hDelete(userid)
        })
        .catch(() => {})
    },
    // 组装一个参数方法
    buildParams () {
      const params = {
        tagName: this.formData.tagName,
        state: this.formData.state,
        page: this.page,
        pagesize: 10
      }
      return params
    },
    // 获取页面铺设数据
    async loadDirectorys () {
      const params = this.buildParams()
      try {
        const results = await getcatalog(params)
        console.log(results)
        this.tableData = results.data.items
        this.total = results.data.counts
      } catch (err) {
        console.log(err)
      }
    },
    // 分页
    Hpager (currentPage) {
      console.log('当前页码' + currentPage)
      this.page = currentPage
      this.loadDirectorys()
    },
    handleSizeChange (val) {
      this.pagesize = val
      if (this.page === 1) {
        this.loadDirectorys()
      }
      console.log(`每页 ${val} 条`)
    },
    // 组装一个搜索参数的方法
    buildSearch () {
      const sparams = {
        tagName: this.searchform.tagName,
        state: this.searchform.state,
        page: this.page,
        pagesize: 10
      }
      return sparams
    },
    // 获取搜索科目详情
    async loadDirectory () {
      const sparams = this.buildSearch()
      try {
        const results = await getcatalog(sparams)
        console.log(results)
        this.tableData = results.data.items
        this.total = results.data.counts
        // this.subjectID=resul ts.data.items.subjectID
        // console.log(this.subjectID)
      } catch (err) {
        console.log(err)
      }
    },
    // 搜索功能
    onSubmit () {
      console.log('submit!')
      this.page = 1
      this.loadDirectory()
    },
    // 清除功能
    resetForm () {
      this.searchform.tagName = ''
      this.searchform.state = ''
    }
  },
  filters: {
    date (addDate) {
      const date = new Date(addDate) // 把定义的时间赋值进来进行下面的转换
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      const hour = date.getHours()
      const minute = date.getMinutes()
      const second = date.getSeconds()
      return (
        year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
      )
    }
  }
}
</script>
<style scoped lang='less'></style>
